﻿using IM.Easy.Api.AccountManage;
using IM.Easy.AuthorizationServices.Constants;
using IM.Easy.AuthorizationServices.Dtos;
using IM.Easy.AuthorizationServices.IServices;
using IM.Easy.Core.AppContext;
using IM.Easy.Core.Attributes;
using IM.Easy.Core.Cache;
using IM.Easy.Core.Exceptions;
using IM.Easy.Core.Extensions;
using IM.Easy.Core.Utils;
using IM.Easy.CoreServices.IServices;
using IM.Easy.Entity.Log;
using IM.Easy.Infrastructure.Constants;
using IM.Easy.LogServices.IServices;
using IM.Easy.SystemServices.IServices;
using IM.Easy.SystemServices.Services;
using Lazy.Captcha.Core;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace IM.Easy.Api.Controllers.Authorization
{
    public class AuthorizeController : ControllerBase
    {
        private readonly IIdentityService _identityService;
        private readonly ICaptcha _captcha;
        private readonly IParamsService _paramsService;
        public AuthorizeController(IIdentityService identityService, IParamsService paramsServiceeds, ICaptcha captcha)
        {
            _identityService = identityService;
            _captcha = captcha;
            _paramsService = paramsServiceeds;
        }

        [HttpPost]
        [Api(Name = "获取AccessToken", AllowAnonymous = true, Required = true)]
        public string GetAccessToken([FromBody] LoginInput input)
        {
            var accessToken = string.Empty;
            LoginUser user;
            var enableCaptcha = string.Equals(_paramsService.GetValue(ParamsConstant.VCode, true)?.Trim(), "on");
            //判断验证码
            if (enableCaptcha)
            {
                if (!_captcha.Validate(input.ConnectionId, input.Captcha)) ExceptionUtils.ThrowBusinessException("验证码错误或已过期");
            }
            //用户验证
            var result = _identityService.GetLoginUser(input);
            if (result.IsSuccess)
            {
                user = result.Data;
                accessToken = _identityService.IssureAccessToken(user);
            }
            else
            {
                ExceptionUtils.ThrowBusinessException(result.Msg);
            }
            return accessToken;
        }

        /// <summary>
        /// 生成图片验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet("captchaImage")]
        [Api(Name = "获取验证码", AllowAnonymous = true, Required = true)]
        public CaptchaDto GetCaptchaImage()
        {
            var vcode = _paramsService.GetValue(ParamsConstant.VCode, true);
            var connectionId = ImApp.Current.GetClientId();
            var info = _captcha.Generate(connectionId, 60);
            var captcha = new CaptchaDto()
            {
                CaptchaEnabled = string.Equals("on", vcode?.Trim()),
                ConnectionId = connectionId,
                Img = info.Base64
            };
            return captcha;
        }
    }
}
